package com.cuit.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.cuit.mapper.ModuleListMapper;
import com.cuit.mapper.RolesMapper;
import com.cuit.pojo.ModuleList;
import com.cuit.service.MenuListService;
import com.cuit.vo.MenuListVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class MenuListServiceImpl implements MenuListService {

    @Autowired
    private ModuleListMapper moduleListMapper;

    @Autowired
    private RolesMapper rolesMapper;

    @Override
    public List<MenuListVo> getMenuListUser(Integer roleId) {
        LambdaQueryWrapper<ModuleList> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.inSql(ModuleList::getModuleId,"select MODULE_ID\n" +
                "from MODULE_USERTYPE mu where mu.ROLE_ID = " + roleId);
        queryWrapper.last("order by module_id");
        List<ModuleList> moduleLists = moduleListMapper.selectList(queryWrapper);
        List<MenuListVo> menuListVoList = changeTree(moduleLists);
        return menuListVoList;
    }

    private List<MenuListVo> changeTree(List<ModuleList> menuLists) {
        List<MenuListVo> menuListVos = new ArrayList<>();
        for (ModuleList menuList : menuLists) {
            if (menuList.getParentmoduleId() == null){
                MenuListVo menuListVo = new MenuListVo();
                BeanUtils.copyProperties(menuList,menuListVo);
                MenuTree(menuLists,menuListVo.getModuleId(),menuListVo);
                menuListVos.add(menuListVo);
            }
        }
        return menuListVos;
    }

    private void MenuTree(List<ModuleList> menuLists, Integer moduleId, MenuListVo menuListVo){

        List<ModuleList> menuLists1 = new ArrayList<>();
        for (ModuleList menuList : menuLists) {
            if (menuList.getParentmoduleId() != null){
                if (menuList.getParentmoduleId().equals(moduleId)){
                    menuLists1.add(menuList);
                }
            }
        }
        menuListVo.setChildren(menuLists1);

    }
}
